package com.tanhua.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.Publish;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.manage.service.VideoService;
import com.tanhua.manage.vo.PageResult;
import com.tanhua.manage.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class VideoServiceImpl implements VideoService {
    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Override
    public PageResult queryVideo(Integer page, Integer pageSize, Long id) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);


        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(id, page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        //查询用户信息
        Map<Long, UserInfo> userInfoMap = this.userInfoApi.queryMapByUserIdList(CollUtil.getFieldValues(records, "userId"));

        List<VideoVo> videoVoList = new ArrayList<>();
        records.forEach(video -> {
            VideoVo videoVo = BeanUtil.toBeanIgnoreError(video, VideoVo.class);
            //查询用户
            UserInfo userInfo = userInfoMap.get(videoVo.getUserId());
            //属性值拷贝
            BeanUtil.copyProperties(userInfo, videoVo, "id", "userId");
            //查询点赞数
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(Convert.toStr(video.getId()))));
            //查询评论数
            videoVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(Convert.toStr(video.getId()))));
            //封装时间
            videoVo.setCreateDate(DateUtil.date(video.getCreated()).toString());
            videoVoList.add(videoVo);
        });

        pageResult.setItems(videoVoList);
        return pageResult;
    }

}
